<?php
/**
 * 会员管理控制器
 * Class MemberController
 */
class MemberController{
    private $data;
    public function __construct()
    {
        $this->data = include './data.php';
    }

    /**
     * 登陆
     */
    public function login(){
        if(IS_POST){
            //获取用户提交的用户名和密码
            $username = $_POST['username'];
            $password = md5($_POST['password']);
            //循环数据库进行判断
            foreach ($this->data as $u){
                //用户名和密码都相同
                if($u['username'] == $username && $u['password'] == $password){
                    $_SESSION['username'] = $username;
                    //如果是7天免登陆
                    if($_POST['auto']){
                        setcookie(session_name(),session_id(),time()+3600 * 24 * 7,'/');
                    }else{//如果不是7天免登陆
                        setcookie(session_name(),session_id(),0,'/');
                    }
                    success('登陆成功','index.php');
                }
            }
            //一定放在循环外面!!!!!
            success('登陆失败','index.php?c=Member&a=login');


        }
        include './View/login.php';
    }

    /**
     * 注册
     */
    public function reg(){
        if(IS_POST){
            //先判断验证码是否正确
            if(strtolower($_POST['code']) != $_SESSION['code']){
                success('验证码错误','index.php?c=Member&a=reg');
            }

            //判断用户名是否重复
            foreach ($this->data as $u){
                if($u['username'] == $_POST['username']){
                    success('用户名已存在','index.php?c=Member&a=reg');
                }
            }
            //追加
            $this->data[] = array(
                'username'=>$_POST['username'],
                'password'=>md5($_POST['password'])
            );
            //写入数据库
            file_put_contents('./data.php',"<?php return " . var_export($this->data,true) . "?>");
            success('注册成功','index.php');
        }
        include './View/reg.php';
    }

    /**
     * 退出登陆
     */
    public function out(){
        session_unset();
        session_destroy();
        success('退出成功','index.php');
    }

    public function code(){
        $code = new Code(NULL,NULL,NULL,1);
        $code->make();
    }

    public function checkUser(){
        $username = $_POST['u'];
        foreach ($this->data as $u) {
            if($u['username'] == $username){
                echo 1;exit;
            }
        }
        echo 0;
    }

}




